<template>
  <div class="note-container">
    <div class="page-header">
      <div class="page-title">笔记管理</div>
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加笔记</el-button>
        <el-button type="success" icon="el-icon-folder" @click="handleCategoryManage">分类管理</el-button>
        <el-button type="warning" icon="el-icon-s-grid" @click="goToSticky">便签墙</el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="标题">
        <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="标签">
        <el-input v-model="searchForm.tags" placeholder="请输入标签" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 分类导航 -->
    <div class="category-nav">
      <el-radio-group v-model="activeCategory" @change="handleCategoryChange">
        <el-radio-button :label="null">全部</el-radio-button>
        <el-radio-button v-for="item in categoryList" :key="item.id" :label="item.id">
          <i v-if="item.icon" :class="item.icon"></i>
          {{ item.name }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 笔记列表 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="note in noteList" :key="note.id" class="note-item">
        <el-card shadow="hover" @click.native="handleView(note)">
          <div class="note-title">{{ note.title }}</div>
          <div class="note-content" v-html="note.content | ellipsisHtml"></div>
          <div class="note-footer">
            <div class="note-tags">
              <el-tag v-for="(tag, index) in note.tags ? note.tags.split(',') : []" :key="index" size="mini" type="info">{{ tag }}</el-tag>
            </div>
            <div class="note-date">{{ note.createTime | formatDate }}</div>
          </div>
          <div class="note-actions">
            <el-button type="text" size="mini" @click.stop="handleEdit(note)">编辑</el-button>
            <el-button type="text" size="mini" @click.stop="handleDelete(note)">删除</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 空状态 -->
    <el-empty v-if="noteList.length === 0 && !loading" description="暂无笔记"></el-empty>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-spinner></el-spinner>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="pagination.pageNum"
        :page-sizes="[12, 24, 36, 48]"
        :page-size.sync="pagination.pageSize"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" @closed="resetForm">
      <el-form ref="noteForm" :model="noteForm" :rules="noteRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="noteForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="noteForm.categoryId" placeholder="请选择分类" clearable style="width: 100%">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor
            v-model="noteForm.content"
            ref="quillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @ready="onEditorReady($event)"
          />
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="noteForm.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog title="笔记详情" :visible.sync="viewDialogVisible" width="800px">
      <div class="note-detail">
        <h2 class="note-detail-title">{{ noteDetail.title }}</h2>
        <div class="note-detail-meta">
          <span v-if="getCategoryName(noteDetail.categoryId)" class="note-detail-category">
            分类：{{ getCategoryName(noteDetail.categoryId) }}
          </span>
          <span class="note-detail-date">{{ noteDetail.createTime | formatDate }}</span>
          <div class="note-detail-tags">
            <el-tag v-for="(tag, index) in noteDetail.tags ? noteDetail.tags.split(',') : []" :key="index" size="small">{{ tag }}</el-tag>
          </div>
        </div>
        <div class="note-detail-content" v-html="noteDetail.content"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEditFromView">编辑</el-button>
      </div>
    </el-dialog>

    <!-- 分类管理对话框 -->
    <el-dialog title="分类管理" :visible.sync="categoryDialogVisible" width="600px">
      <div class="category-manage">
        <div class="category-header">
          <el-button type="primary" size="small" @click="handleAddCategory">添加分类</el-button>
        </div>
        <el-table :data="categoryList" style="width: 100%" v-loading="categoryLoading">
          <el-table-column prop="name" label="分类名称" />
          <el-table-column prop="icon" label="图标">
            <template slot-scope="scope">
              <i v-if="scope.row.icon" :class="scope.row.icon"></i>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEditCategory(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDeleteCategory(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog
        width="500px"
        title="添加/编辑分类"
        :visible.sync="categoryFormVisible"
        append-to-body
      >
        <el-form ref="categoryForm" :model="categoryForm" :rules="categoryRules" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="图标">
            <el-input v-model="categoryForm.icon" placeholder="请输入图标类名" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="categoryFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="categorySubmitLoading" @click="submitCategoryForm">确定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { getNoteList, addNote, updateNote, deleteNote, getNoteDetail } from '@/api/note'
import { getNoteCategoryList, addNoteCategory, updateNoteCategory, deleteNoteCategory } from '@/api/noteCategory'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  name: 'Note',
  components: {
    quillEditor
  },
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 100) {
        return value.slice(0, 100) + '...'
      }
      return value
    },
    ellipsisHtml(value) {
      if (!value) return ''
      // 创建临时元素以去除HTML标签
      const div = document.createElement('div')
      div.innerHTML = value
      const text = div.textContent || div.innerText || ''
      if (text.length > 100) {
        return text.slice(0, 100) + '...'
      }
      return text
    },
    formatDate(value) {
      if (!value) return ''
      const date = new Date(value)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        title: '',
        categoryId: null,
        tags: ''
      },
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 12,
        total: 0
      },
      // 笔记列表
      noteList: [],
      // 加载状态
      loading: false,
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加笔记',
      submitLoading: false,
      // 表单
      noteForm: {
        id: null,
        title: '',
        categoryId: null,
        content: '',
        tags: ''
      },
      // 表单校验规则
      noteRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      // 查看对话框
      viewDialogVisible: false,
      noteDetail: {},
      // 富文本编辑器配置
      editorOption: {
        placeholder: '请输入笔记内容...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean'],
            ['link', 'image']
          ]
        }
      },
      // 分类相关
      categoryList: [],
      activeCategory: null,
      categoryDialogVisible: false,
      categoryLoading: false,
      categoryFormVisible: false,
      categorySubmitLoading: false,
      categoryForm: {
        id: null,
        name: '',
        icon: '',
        sort: 0
      },
      categoryRules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchCategoryList()
    this.fetchData()
  },
  methods: {
    // 编辑器相关方法
    onEditorBlur(quill) {
      // console.log('编辑器失去焦点', quill)
    },
    onEditorFocus(quill) {
      // console.log('编辑器获得焦点', quill)
    },
    onEditorReady(quill) {
      // console.log('编辑器准备完成', quill)
    },
    // 获取分类列表
    fetchCategoryList() {
      this.categoryLoading = true
      getNoteCategoryList()
        .then(response => {
          this.categoryList = response.data
          this.categoryLoading = false
        })
        .catch(() => {
          this.categoryLoading = false
        })
    },
    // 获取笔记列表
    fetchData() {
      this.loading = true
      getNoteList({
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        title: this.searchForm.title,
        categoryId: this.searchForm.categoryId,
        tag: this.searchForm.tags
      })
        .then(response => {
          const { data } = response
          this.noteList = data.records
          this.pagination.total = data.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        title: '',
        categoryId: null,
        tags: ''
      }
      this.activeCategory = null
      this.handleSearch()
    },
    // 分页大小变化
    handleSizeChange() {
      this.fetchData()
    },
    // 页码变化
    handleCurrentChange() {
      this.fetchData()
    },
    // 分类变化
    handleCategoryChange(categoryId) {
      this.searchForm.categoryId = categoryId
      this.handleSearch()
    },
    // 获取分类名称
    getCategoryName(categoryId) {
      if (!categoryId) return ''
      const category = this.categoryList.find(item => item.id === categoryId)
      return category ? category.name : ''
    },
    // 添加笔记
    handleAdd() {
      this.dialogTitle = '添加笔记'
      this.noteForm = {
        id: null,
        title: '',
        categoryId: null,
        content: '',
        tags: ''
      }
      this.dialogVisible = true
    },
    // 查看笔记
    handleView(row) {
      this.viewDialogVisible = true
      getNoteDetail(row.id)
        .then(response => {
          this.noteDetail = response.data
        })
    },
    // 编辑笔记
    handleEdit(row) {
      this.dialogTitle = '编辑笔记'
      getNoteDetail(row.id)
        .then(response => {
          this.noteForm = { ...response.data }
          this.dialogVisible = true
        })
    },
    // 从查看对话框进入编辑
    handleEditFromView() {
      this.viewDialogVisible = false
      this.dialogTitle = '编辑笔记'
      this.noteForm = { ...this.noteDetail }
      this.dialogVisible = true
    },
    // 删除笔记
    handleDelete(row) {
      this.$confirm('确认删除该笔记吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteNote(row.id)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.fetchData()
            })
        })
        .catch(() => {})
    },
    // 提交表单
    submitForm() {
      this.$refs.noteForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.noteForm.id) {
            // 更新
            updateNote(this.noteForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          } else {
            // 添加
            addNote(this.noteForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      if (this.$refs.noteForm) {
        this.$refs.noteForm.resetFields()
      }
    },
    // 分类管理
    handleCategoryManage() {
      this.categoryDialogVisible = true
      this.fetchCategoryList()
    },
    // 添加分类
    handleAddCategory() {
      this.categoryForm = {
        id: null,
        name: '',
        icon: '',
        sort: 0
      }
      this.categoryFormVisible = true
    },
    // 编辑分类
    handleEditCategory(row) {
      this.categoryForm = { ...row }
      this.categoryFormVisible = true
    },
    // 删除分类
    handleDeleteCategory(row) {
      this.$confirm('确认删除该分类吗？删除后，该分类下的笔记将变为无分类状态。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteNoteCategory(row.id)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.fetchCategoryList()
            })
        })
        .catch(() => {})
    },
    // 提交分类表单
    submitCategoryForm() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          this.categorySubmitLoading = true
          if (this.categoryForm.id) {
            // 更新
            updateNoteCategory(this.categoryForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.categoryFormVisible = false
                this.fetchCategoryList()
                this.categorySubmitLoading = false
              })
              .catch(() => {
                this.categorySubmitLoading = false
              })
          } else {
            // 添加
            addNoteCategory(this.categoryForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.categoryFormVisible = false
                this.fetchCategoryList()
                this.categorySubmitLoading = false
              })
              .catch(() => {
                this.categorySubmitLoading = false
              })
          }
        }
      })
    },
    // 跳转到便签墙
    goToSticky() {
      this.$router.push('/sticky')
    }
  }
}
</script>

<style lang="scss" scoped>
.note-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .category-nav {
    margin-bottom: 20px;
    
    .el-radio-button {
      margin-bottom: 10px;
    }
  }
  
  .note-item {
    margin-bottom: 20px;
    
    .el-card {
      height: 200px;
      position: relative;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }
    }
    
    .note-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .note-content {
      font-size: 14px;
      color: #606266;
      height: 80px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 4;
      -webkit-box-orient: vertical;
    }
    
    .note-footer {
      position: absolute;
      bottom: 40px;
      left: 20px;
      right: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .note-tags {
        display: flex;
        flex-wrap: wrap;
        
        .el-tag {
          margin-right: 5px;
          margin-bottom: 5px;
        }
      }
      
      .note-date {
        font-size: 12px;
        color: #909399;
      }
    }
    
    .note-actions {
      position: absolute;
      bottom: 10px;
      right: 20px;
    }
  }
  
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: center;
  }
  
  .note-detail {
    padding: 0 20px;
    
    .note-detail-title {
      text-align: center;
      margin-bottom: 20px;
    }
    
    .note-detail-meta {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      flex-wrap: wrap;
      
      .note-detail-category,
      .note-detail-date {
        color: #909399;
        margin-bottom: 10px;
      }
      
      .note-detail-tags {
        .el-tag {
          margin-left: 5px;
        }
      }
    }
    
    .note-detail-content {
      line-height: 1.8;
      white-space: pre-wrap;
    }
  }
  
  .category-manage {
    .category-header {
      margin-bottom: 15px;
      text-align: right;
    }
  }
  
  // 富文本编辑器样式
  .quill-editor {
    height: 350px;
    margin-bottom: 20px;
  }
  
  .ql-container {
    min-height: 300px;
  }
}
</style>

<style>
/* 全局样式，不使用scoped */
.ql-editor {
  min-height: 300px;
  font-size: 14px;
  line-height: 1.8;
}

.note-detail-content {
  line-height: 1.8;
}

.note-detail-content img {
  max-width: 100%;
  height: auto;
}

.note-detail-content p {
  margin-bottom: 1em;
}

.note-detail-content h1,
.note-detail-content h2,
.note-detail-content h3,
.note-detail-content h4,
.note-detail-content h5,
.note-detail-content h6 {
  margin-top: 1em;
  margin-bottom: 0.5em;
}

.note-detail-content blockquote {
  border-left: 4px solid #ccc;
  margin-bottom: 5px;
  margin-top: 5px;
  padding-left: 16px;
  background-color: #f8f8f8;
}

.note-detail-content pre {
  background-color: #f8f8f8;
  border-radius: 3px;
  padding: 10px;
  overflow: auto;
}

.note-detail-content code {
  background-color: #f0f0f0;
  border-radius: 3px;
  padding: 2px 4px;
  font-family: monospace;
}
</style> 